import { BrowserWindow, ipcMain, protocol, dialog, app, Menu } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'

Menu.setApplicationMenu(null)
const ws = require('nodejs-websocket')
const urlencode = require('urlencode')
// const fs = require('fs')
// const path = require('path')
protocol.registerSchemesAsPrivileged([
  {
    scheme: 'app',
    privileges: {
      secure: true,
      standard: true,
      stream: true
    }
  }
])

let mainWindow, socket
// const configPath = path.resolve(
//   path.dirname(app.getPath('exe')),
//   'socket.js'
// )
// fs.readFile(configPath, 'UTF-8', (err, data) => {
//   if (err) {
//     dialog.showMessageBox({ message: err.message })
//   } else {
//     console.log(data)
//   }
// })

export function createWindow () {
  mainWindow = new BrowserWindow({
    width: 750,
    height: 650,
    minWidth: 750,
    minHeight: 650,
    // frame: false,
    backgroundColor: '#eaeaea',
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) mainWindow.webContents.openDevTools()
  } else {
    createProtocol('app')
    mainWindow.loadURL('app://./index.html')
  }
}

ipcMain.on('fullScreen', () => {
  if (mainWindow.isFullScreen()) {
    mainWindow.setFullScreen(false)
  } else {
    mainWindow.setFullScreen(true)
  }
})

ipcMain.on('reload', () => {
  mainWindow.reload()
})

ipcMain.on('close', () => {
  mainWindow.close()
})

ipcMain.on('debug', () => {
  if (mainWindow.isDevToolsOpened()) {
    mainWindow.closeDevTools()
  } else {
    mainWindow.openDevTools()
  }
})

ipcMain.on('createWebsocketServer', (event, port) => {
  console.log('createWebsocketServer: ' + port)
  createServer(port)
})

ipcMain.on('closeWebsocketServer', () => {
  closeServer()
})

ipcMain.on('sendAll', (event, message) => {
  sendAll(message)
})

const createServer = (port) => {
  socket = ws.createServer((conn) => {
    const identity = urlencode.decode(conn.path.substring(1))
    console.log('[' + identity + ']' + ' 连接成功!')
    receiveMessage({
      identity: '服务器 - 广播',
      text: '[' + identity + ']' + ' 连接成功!',
      time: new Date()
    })
    conn.on('text', (text) => {
      console.log('身份: ', identity)
      console.log('text:' + text)
      receiveMessage({
        identity: identity,
        text: text,
        time: new Date()
      })
    })
    conn.on('close', function (code, reason) {
      console.log('[' + identity + ']' + ' 连接关闭!')
      receiveMessage({
        identity: '服务器 - 广播',
        text: '[' + identity + ']' + ' 连接关闭!',
        time: new Date()
      })
    })
    conn.on('error', function (code, reason) {
      console.log('异常关闭', code, reason)
    })
  }).listen(port)
}

const closeServer = () => {
  console.log(socket)
  socket.connections.forEach(conn => {
    conn.close()
  })
  socket.close((res) => {
    console.log(res)
  })
}

const sendAll = (message) => {
  socket.connections.forEach(conn => {
    conn.sendText(message)
  })
}

const receiveMessage = (message) => {
  mainWindow.webContents.send('receiveMessage', message)
}
